<template>
  <div class="app-container">
    <div>
      <el-button type="primary" plain @click="showLiuzhuanDialog"
        >新建事项申请</el-button
      >
    </div>
    <div style="padding: 10px" />
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column label="状态" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.approvalState == 0" type="warning"
            >审核</el-tag
          >
          <el-tag v-if="scope.row.approvalState == 1" type="success"
            >通过</el-tag
          >
          <el-tag v-if="scope.row.approvalState == 2" type="danger"
            >拒绝</el-tag
          >
          <el-tag v-if="scope.row.approvalState == 3" type="info">撤销</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="发起部门" align="center" width="100px">
        <template slot-scope="scope">
          <el-tag> {{ scope.row.receiveUnit }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="发文时间" align="center" width="110px">
        <template slot-scope="scope">
          {{ getFormatedTimeStr(scope.row.receiveData) }}
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>

      <el-table-column label="内容摘要" align="center">
        <template slot-scope="scope">
          {{ scope.row.content }}
        </template>
      </el-table-column>

      <el-table-column label="相关附件" align="center">
        <template slot-scope="scope">
          <p
            v-for="(item, index) in scope.row.accessoryBeans"
            :key="index"
            style=""
          >
            <el-link :href="item.url" type="primary" target="_blank">{{
              item.name
            }}</el-link>
          </p>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="250px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            plain
            @click="seeDetail(scope.row.id)"
            >详情
          </el-button>
          <el-button
            size="mini"
            type="warning"
            plain
            @click="singlePrint(scope.row.id)"
            >打印
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px" />
    <el-pagination
      :current-page="pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="dataTotal"
      @size-change="onPageSizeChange"
      @current-change="onCurrentPageChange"
    />

    <el-dialog
      :visible.sync="liuzhuanDialog.visible"
      width="40%"
      :close-on-click-modal="false"
      top="5vh"
      center
      :show-close="false"
    >
      <div>
        <el-form
          ref="form"
          size="mini"
          label-position="left"
          label-width="100px"
        >
          <el-row>
            <!-- 左侧 -->
            <el-col :span="11">
              <div class="title"><i class="el-icon-document" /> 申请单</div>
              <el-form-item label="发起部门">
                <el-input v-model="liuzhuanForm.danwei" />
              </el-form-item>

              <el-form-item label="发文时间">
                <el-date-picker
                  v-model="liuzhuanForm.chengwenDate"
                  placeholder="选择日期"
                  style="width: 100%"
                />
              </el-form-item>

              <el-form-item label="标题">
                <el-input v-model="liuzhuanForm.biaoti" />
              </el-form-item>

              <el-form-item label="内容摘要">
                <el-input
                  v-model="liuzhuanForm.zhaiyao"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入内容"
                />
              </el-form-item>

              <el-form-item label="附件">
                <el-upload
                  ref="attaches"
                  :headers="upload.headers"
                  :action="upload.action"
                  :data="upload.params"
                  :limit="1"
                  :on-success="uploadAttachSuccess"
                  :before-upload="beforeUpload"
                  multiple
                >
                  <el-button size="mini" type="primary" plain
                    >点击上传附件</el-button
                  >
                </el-upload>
              </el-form-item>
            </el-col>
            <!-- 右侧 -->
            <el-col :span="11" :offset="2">
              <div class="title"><i class="el-icon-s-check" /> 审核流程</div>
              <div v-for="(item, index) in liuzhuanForm.auditors" :key="index">
                <!-- 箭头：第一个不显示 -->
                <div v-if="index > 0" class="step-arrow">
                  <el-row>
                    <el-col :span="8">
                      <div><i class="el-icon-caret-bottom" /></div>
                    </el-col>
                  </el-row>
                </div>
                <!-- 步骤样式 -->
                <div class="step">
                  <el-row>
                    <el-col :span="8">
                      <div class="step-info-left">{{ item.stepName }}</div>
                    </el-col>
                    <el-col :span="16">
                      <div class="step-info-right">
                        {{
                          item.stepName == "分管领导" &&
                          liuzhuanForm.auditors[0].sta == 0
                            ? "待选择"
                            : item.name
                        }}
                      </div>
                    </el-col>
                  </el-row>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="liuzhuanDialog.visible = false">关 闭</el-button>
        <el-button type="primary" @click="clickApply()">提 交</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title=""
      width="60%"
      :visible.sync="detailDialog.visible"
      top="5vh"
    >
      <xianjianfawen-detail :id="detailDialog.id" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="detailDialog.visible = false"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import printJS from "print-js";
import { getToken } from "@/utils/auth";
import { websock } from "@/websock";
import moment from "moment";
import { getXinjianList, addFawen,printDocument } from "@/api2/xinjianfawen.js";
import { quchongAuditors } from "@/utils/utils";
import xianjianfawenDetail from "../../components/details/xianjianfawenDetail";
const base_url = process.env.VUE_APP_BASE_APITwo;
export default {
  components: { xianjianfawenDetail },
  filters: {
    statusFilter(sta) {
      const statusMap = {
        1: "info",
        2: "success",
        3: "danger",
      };
      return statusMap[sta];
    },
  },
  data() {
    return {
      props: {
        multiple: true,
      },
      printDialog: {
        visible: false,
        checkedKeys: [],
      },
      upload: {
        headers: { Authorization: getToken(), platform: "WEB" },
        action: base_url + "/common/upload",
        open: false,
        params: {},
      },
      loginId: JSON.parse(sessionStorage.getItem("loginUserinfo")).uid,
      list: null,
      listLoading: true,
      pageNum: 1,
      pageSize: 10,
      dataTotal: 0,
      userList: [],
      // 添加员工
      liuzhuanForm: {
        bianhao: "",
        danwei: "",
        zhaiyao: "",
        biaoti: "",
        chengwenDate: "",
        readers: [],
        accessoryBeans: [],
        auditors: [],
      },
      liuzhuanDialog: {
        visible: false,
        bianhao: "",
        danwei: "",
        wenhao: "",
        biaoti: "",
        chengwenDate: "",
        zhaiyao: "",
        readers: [],
        attaches: [],
        auditors: [],
      },
      detailDialog: {
        visible: false,
        id: 0,
      },
    };
  },
  async created() {
    this.getList();

    const res = await websock.getContactList();
    console.log("created", res);
    const userList = [];
    for (let i = 0; i !== res.length; i++) {
      userList.push({
        value: i + "",
        label: res[i].name,
        children: [],
      });
      for (let j = 0; j !== res[i].userList.length; j++) {
        userList[i].children.push({
          value: JSON.stringify({
            uid: res[i].userList[j].uid,
            name: res[i].userList[j].name,
          }),
          label: res[i].userList[j].name,
        });
      }
    }
    this.userList = userList;

    const auditors = await websock.getAuditors({ typ: 24 });
    console.log("auditors", auditors);
    this.liuzhuanForm.auditors = auditors;
  },
  methods: {
    singlePrint(id) {
      console.log(id);
      let that = this;
      that.printDialog.checkedKeys = [id];
      that.printClick();
    },
    async printClick() {
      const res = await printDocument(this.printDialog.checkedKeys.join());
      console.log(res);
      printJS(res.data.url);
    },
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = "YYYY-MM-DD") {
      return moment(stamp).format(str);
    },
    getList() {
      this.listLoading = true;
      getXinjianList({
        uid: this.loginId,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }).then((data) => {
        this.listLoading = false;
        this.list = data.data;
        this.dataTotal = data.total;
      });
    },
    // ----------
    uploadAttachSuccess(res, file) {
      console.log("upload attach success", res, file);
      if (res.code !== 0) {
        return this.$message.error(res.message || "error");
      } else {
        this.liuzhuanForm.accessoryBeans.push({
          url: res.data.url,
          name: res.data.fileName,
        });
      }
    },
    //上传
    beforeUpload(rawFile) {
      console.log(rawFile);
      const isLt5M = rawFile.size / 1024 / 1024 < 20;
      if (!isLt5M) {
        this.$message.error("文件大小限制在 20MB 内!");
        return false;
      }
    },
    onPageSizeChange(val) {
      this.pageSize = val;
      this.getList();
    },
    onCurrentPageChange(val) {
      this.pageNum = val;
      this.getList();
    },
    // 显示添加员工界面
    showLiuzhuanDialog() {
      this.liuzhuanDialog.visible = true;
      this.liuzhuanForm.danwei = "";
      this.liuzhuanForm.biaoti = "";
      let nowDate = new Date();
      let date = {
        // 获取当前年份
        year: nowDate.getFullYear(),
        //获取当前月份
        month: nowDate.getMonth() + 1,
        //获取当前日期
        date: nowDate.getDate(),
      };
      this.liuzhuanForm.chengwenDate = new Date(
        date.year + "-" + date.month + "-" + date.date
      );
      // this.liuzhuanForm.chengwenDate = ''
      this.liuzhuanForm.zhaiyao = "";
      this.liuzhuanForm.readers = [];
      this.liuzhuanForm.attaches = [];
      if (this.$refs.attaches) this.$refs.attaches.uploadFiles = [];
    },
    async clickApply() {
      console.log("click apply", this.liuzhuanDialog);
      if (!this.liuzhuanForm.danwei)
        return this.$message.error("请输入发起部门");
      if (!this.liuzhuanForm.biaoti) return this.$message.error("请输入标题");
      if (!this.liuzhuanForm.chengwenDate)
        return this.$message.error("请选择发文时间");
      if (!this.liuzhuanForm.zhaiyao)
        return this.$message.error("请输入内容摘要");

      // if (this.liuzhuanDialog.readers.length == 0) return this.$message.error('请选择分发范围')

      if (this.liuzhuanForm.auditors.length == 0)
        return this.$message.error("请选择审核人");

      // const auditors = []
      // for (let i = 0; i != this.liuzhuanForm.auditors.length; i++) {
      //     auditors.push({ uid: this.liuzhuanForm.auditors[i].uid, stepName: this.liuzhuanForm.auditors[i].stepName || this.liuzhuanForm.auditors[i].positionName })
      // }

      // // const readers = []
      // // for (let i = 0; i != this.liuzhuanDialog.readers.length; i++) {
      // //   readers.push(JSON.parse(this.liuzhuanDialog.readers[i][1]))
      // // }

      let auditors = [];
      for (let i = 0; i != this.liuzhuanForm.auditors.length; i++) {
        auditors.push({
          ts: "",
          sta: 0,
          msg: "",
          uid: this.liuzhuanForm.auditors[i].uid,
          name: this.liuzhuanForm.auditors[i].name,
          signimg: "",
          stepName:
            this.liuzhuanForm.auditors[i].stepName ||
            this.liuzhuanForm.auditors[i].positionName,
        });
      }
      let OldObject = auditors.reduce((o, n, i) => {
        o["auditor" + i] = {
          ts: "",
          msg: "",
          sta: 0,
          signimg: n.signimg,
          uid: n.uid,
          stepName: n.stepName,
          name: n.name,
        };
        return o;
      }, {});
      const params = {
        receiveUnit: this.liuzhuanForm.danwei,
        // receiveNumber: this.liuzhuanForm.wenhao,
        // receiveFontSize: this.liuzhuanForm.zihao,
        title: this.liuzhuanForm.biaoti,
        receiveData: this.liuzhuanForm.chengwenDate,
        content: this.liuzhuanForm.zhaiyao,
        // url: this.liuzhuanForm.pics,
        accessoryBeans: this.liuzhuanForm.accessoryBeans || [],
        // readers,
        approvalProcessDataBeanMap: OldObject,
      };
      try {
        await addFawen(params);
        this.$message.success("申请成功,请等待审核");
        this.liuzhuanDialog.visible = false;
        this.getList();
      } catch (err) {
        this.$message.error(err.message || "error");
      }
    },
    seeDetail(id) {
      this.detailDialog.visible = true;
      this.detailDialog.id = id;
    },
  },
};
</script>

<style>
@import url("../../styles/form.css");
</style>
